package com.ai.trickycards.utils

import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.EditText
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.core.animation.doOnEnd
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

fun Fragment.onLifecycleState(
    state: Lifecycle.State = Lifecycle.State.CREATED,
    block: suspend CoroutineScope.() -> Unit
) = lifecycleScope.launch {
    repeatOnLifecycle(state, block)
}

fun ComponentActivity.onLifecycleState(
    state: Lifecycle.State = Lifecycle.State.CREATED,
    block: suspend CoroutineScope.() -> Unit
) = lifecycleScope.launch {
    repeatOnLifecycle(state, block)
}

fun TextView.getString() = text.toString().trim()
fun EditText.getString() = text.toString().trim()
fun EditText.setString(text: String) {
    setText(text)
    setSelection(length())
}

@SuppressLint("SetTextI18n")
fun TextView.startAnimationInt(
    prefix: String? = null,
    fromValue: Int,
    toValue: Int,
    startDelay: Long = 0,
    duration: Long = 800,
    interpolator: TimeInterpolator = LinearInterpolator(),
    doEnd: (() -> Unit)? = null
) {
    ValueAnimator.ofInt(fromValue, toValue).apply {
        setDuration(duration)
        setStartDelay(startDelay)
        setInterpolator(interpolator)
        addUpdateListener {
            val value = it.animatedValue as Int
            text = "${prefix ?: ""}$value"
        }
        doOnEnd {
            doEnd?.invoke()
        }
        start()
    }
}

fun ViewGroup.getChildren(): List<View> {
    return List(childCount) {
        getChildAt(it)
    }
}

fun View.setMargin(
    left: Int = Int.MIN_VALUE,
    top: Int = Int.MIN_VALUE,
    right: Int = Int.MIN_VALUE,
    bottom: Int = Int.MIN_VALUE
) {
    (layoutParams as? ViewGroup.MarginLayoutParams)?.let {
        it.leftMargin = if (left != Int.MIN_VALUE) left else it.leftMargin
        it.topMargin = if (top != Int.MIN_VALUE) top else it.topMargin
        it.rightMargin = if (right != Int.MIN_VALUE) right else it.rightMargin
        it.bottomMargin = if (bottom != Int.MIN_VALUE) bottom else it.bottomMargin
    }
}

fun Context.hasPermission(permission: String): Boolean {
    return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
}